package com.xkw.autocode.web.common;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

/**
 * 统一异常处理
 * 
 * @author xiangkaiwei
 *
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);
	
	private static final String EXCEPTION_STR = "exception";
	
	@ExceptionHandler(value = Exception.class)
	@ResponseBody
	public Object jsonErrorHandler(HttpServletRequest request,HttpServletResponse response, Exception e)  {
		
		LOGGER.error("全局异常处理：",e);
		
		// 判断ajax请求
		if (request.getHeader("x-requested-with") != null
				&& request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) { // 如果是ajax请求响应头会有，x-requested-with
			
			response.setHeader("sessionstatus", EXCEPTION_STR);
			
			return e + " : " + e.getMessage();
		} else {
			ModelAndView mv = new ModelAndView(EXCEPTION_STR);
			mv.addObject("url", request.getRequestURL());
			mv.addObject(EXCEPTION_STR,e + " : " + e.getMessage());
			return mv;
		}
	}
}
